const {IncomingMessage} = require('http');
const ws = require('ws');

interface User {
    userId: string;
    username: string;
    ws: typeof ws;
}

const webSocketServer = new ws.Server({ port: 8080 });
const users = new Map<string, User>();

webSocketServer.on('listening', () => {
    console.log('webSocket服务开始监听');
});

webSocketServer.on('connection', (socket: typeof ws, request: typeof IncomingMessage) => {
    let userId = '';
    console.log('webSocket服务连接成功');

    socket.on('message', (message: Buffer) => {
        try {
            const data = JSON.parse(message.toString());
            console.log('收到客户端消息：', data);

            switch(data.type) {
                case 'login':
                    userId = Date.now().toString();
                    users.set(userId, {
                        userId,
                        username: data.username,
                        ws: socket  // 这里应该是 socket 而不是 ws
                    });
                    
                    socket.send(JSON.stringify({  // 使用 socket 而不是 ws
                        type: 'login_response',  // 改为 login_response 以匹配前端
                        userId
                    }));
                    
                    broadcastUsersList();
                    break;

                case 'chat_message':
                    const targetUser = users.get(data.to);
                    if(targetUser) {
                        const messageData = {
                            type: 'chat_message',
                            from: userId,
                            to: data.to,
                            message: data.message
                        };
                        
                        targetUser.ws.send(JSON.stringify(messageData));
                        socket.send(JSON.stringify(messageData));
                    }
                    break;
            }

            if(message.toString() === 'terminate') {
                socket.close();
                setTimeout(() => {
                    webSocketServer.close();
                }, 1000);
            }
        } catch (error) {
            console.error('消息处理错误:', error);
        }
    });

    socket.on('close', (code: number, reason: string) => {
        if (userId) {
            users.delete(userId);
            broadcastUsersList();
        }
        console.log('webSocket服务关闭', code, reason);
    });

    socket.on('error', (error: Error) => {
        console.log('webSocket服务错误', error);
    });

    socket.on('ping', (data: Buffer) => {
        console.log('收到客户端心跳', data);
        socket.pong(data);
    });

    const ip = request.headers['x-forwarded-for'] || request.socket.remoteAddress;
    console.log(ip + '连接成功');
});

function broadcastUsersList() {
    const usersList = Array.from(users.values()).map(user => ({
        userId: user.userId,
        username: user.username
    }));

    webSocketServer.clients.forEach((client: typeof ws) => {
        if (client.readyState === ws.OPEN) {
            client.send(JSON.stringify({
                type: 'users_list',
                users: usersList
            }));
        }
    });
}